package com.kinghunt.misp.web.context;

import com.kinghunt.misp.common.constant.RequestConstants;
import com.kinghunt.misp.common.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ApiContext {
    private static final ThreadLocal<Map<String, String>> REQUEST_HEADER_THREAD_LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<ApiUser> API_USER_THREAD_LOCAL = new ThreadLocal<>();

    public static void init(HttpServletRequest httpServletRequest) {
        cleanContext();
        Enumeration<String> headers = httpServletRequest.getHeaderNames();
        Map<String, String> headerMap = new HashMap<>();
        if (headers != null) {
            while (headers.hasMoreElements()) {
                String header = headers.nextElement();
                headerMap.put(header, httpServletRequest.getHeader(header));
            }
        }
        REQUEST_HEADER_THREAD_LOCAL.set(headerMap);
        initApiUser(headerMap);
    }

    public static void cleanContext() {
        REQUEST_HEADER_THREAD_LOCAL.remove();
        API_USER_THREAD_LOCAL.remove();
    }

    private static void initApiUser(Map<String, String> headerMap) {
        ApiUser apiUser = new ApiUser();
        String token = headerMap.get(RequestConstants.TOKEN_HEADER_NAME);
        long userId = TokenUtils.toUserId(token);
        apiUser.setUserId(userId);
        API_USER_THREAD_LOCAL.set(apiUser);
    }

    public static ApiUser apiUser() {
        return API_USER_THREAD_LOCAL.get();
    }

    public static Map<String, String> requestHeader() {
        return REQUEST_HEADER_THREAD_LOCAL.get();
    }
}
